<template>
  <div class="container">
    <el-card class="center-card">
      <el-form :model="formData" :rules="rules" label-width="80px" class="login-form"      ref="formRef">
        <el-text class="welcome-title" size="large">观弈零代码平台--重置密码</el-text>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="手机号" name="phoneTab">
            <el-input v-model="formData.phone" placeholder="请输入手机号"></el-input>
            <el-input style="margin-top: 5px;"  v-model="formData.verifyCode" placeholder="请输入短信验证码"> <template #append><el-button v-if="activeName === 'phoneTab'" :disabled="isCounting" @click="sendVerifyCode">{{ countdownText }}</el-button></template></el-input>
            <el-input type="password" style="margin-top: 5px;"  v-model="formData.password" placeholder="请输入密码"></el-input>
            <el-input type="password" style="margin-top: 5px;"  v-model="formData.confirmPassword" placeholder="请输入确认密码"></el-input>
          </el-tab-pane>
          <el-tab-pane label="邮箱" name="mailTab">
            <el-input v-model="formData.email" placeholder="请输入邮箱"></el-input>
            <el-input style="margin-top: 5px;"  v-model="formData.verifyCode" placeholder="请输入邮箱验证码"><template #append><el-button v-if="activeName === 'mailTab'" :disabled="isCounting" @click="sendVerifyCode">{{ countdownText }}</el-button></template></el-input>
            <el-input type="password" style="margin-top: 5px;"  v-model="formData.password" placeholder="请输入密码"></el-input>
            <el-input type="password" style="margin-top: 5px;"  v-model="formData.confirmPassword" placeholder="请输入确认密码"></el-input>
          </el-tab-pane>
        </el-tabs>
        <el-button :loading="loading" type="primary" @click="submitForm">确认修改</el-button>
        <el-button :loading="loading" type="primary" @click="goLogin">返回登录</el-button>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {ref, watchEffect, onMounted, watch} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import { sendSmsVerifyCode, sendMailVerifyCode,smsVerifyCode,mailVerifyCode,loginMixed} from '@/api/login';
import { ElForm,   ElMessage } from 'element-plus';

import { changePasword } from "@/api/login";

const formData = ref({
  phone: '',
  email: '',
  password: '',
  confirmPassword:'',
  verifyCode: ''
});
const formRef = ref<InstanceType<typeof ElForm>>();
const activeName = ref('phoneTab');
const verifyModeText = ref('切换消息码登录');
const showVerifyCode = ref(false);
const codeUrl = ref("");
// 验证码开关
const captchaEnabled = ref(true);
const rules = {
  phone: [
    {
      validator: (rule, value, callback) => {
        if (value === '') return callback();
        if (!/^1[3456789]\d{9}$/.test(value)) {
          return callback(new Error('手机号格式错误'));
        }
        callback();
      },
      trigger: ['blur', 'change']
    }
  ],
  email: [
    {
      validator: (rule, value, callback) => {
        if (value === '') return callback();
        if (!/.+@.+\..+/.test(value)) {
          return callback(new Error('邮箱格式错误'));
        }
        callback();
      },
      trigger: 'blur'
    }
  ]
};

const route = useRoute();
const router = useRouter();
const loading = ref(false);
const redirect = ref(undefined);

watch(route, (newRoute) => {
  redirect.value = newRoute.query && newRoute.query.redirect;
}, { immediate: true });

async function submitForm() {
  //debugger;
  let data = {
    mobile: '',
    mail: '',
    password: '',
    verifyCode:''
  }
  //比较两个密码是否相同
  if(formData.value.password!=formData.value.confirmPassword){
    ElMessage.error("密码和确认密码不相同！")
    return;
  }
  if(formData.value.verifyCode==''){
    ElMessage.error("请输入验证码！")
    return;
  }
  loading.value = true;
  if (activeName.value === 'phoneTab') {
    data.mobile = formData.value.phone
  } else {
    data.mail = formData.value.email
  }

  data.password = formData.value.password;
  data.verifyCode = formData.value.verifyCode;
  try {
    let res = await changePasword(data);
    if (res.code == 200) {
      if (res.data) {
        ElMessage.success('密码修改成功!')
      } else {
        ElMessage.error(res.msg);
      }
    } else {
      ElMessage.error(res.msg);
    }
    loading.value = false;
  }catch(error){
    loading.value = false;
  }
}

function goLogin(){
  router.push("/login")

}


const isCounting = ref(false);
const countdownText = ref('发送验证码');
let countdownTimeout: ReturnType<typeof setTimeout> | null = null;

function startCountdown() {
  let remainingTime = 60;
  isCounting.value = true;
  countdownText.value = `${remainingTime}s 后重新发送`;
  const intervalId = setInterval(() => {
    remainingTime--;
    if (remainingTime > 0) {
      countdownText.value = `${remainingTime}s 后重新发送`;
    } else {
      clearInterval(intervalId);
      isCounting.value = false;
      countdownText.value = '发送验证码';
    }
  }, 1000);
}

function sendVerifyCode() {
  formRef.value?.validate((valid) => {
    if (valid) {
      if (activeName.value === 'phoneTab') {
        if(formData.value.phone.length==11) {
          sendSmsVerifyCode(formData.value.phone).then(() => {
            startCountdown();
          });
        }else{
          ElMessage.error('无效的手机号！');
        }
      } else {
        sendMailVerifyCode(formData.value.email).then(() => {
          startCountdown();
        });
      }
    } else {
      console.log('验证失败');
    }
  });

}


onMounted(() => {
  // 初始化操作
});

</script>

<style scoped>
.login-form {
  width: 300px;
  margin: auto;
}
.welcome-title {
  margin-top: 10px;
  font-size: 22px;
  font-weight: 600;
  line-height: 30px;
  color: #1f2329;
}
.switch-title {
  margin-top: 10px;
  font-size: 12px;
  line-height: 30px;
  color: #1764d7;
}
.login-form > * {
  margin-bottom: 10px;
}

.login-form .el-form-item__label span {
  cursor: pointer;
}

.register-link {
  text-align: center;
  margin-top: 10px;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  height: 80vh;           /* 设置容器高度为视口高度 */
}

.center-card {
  width: 500px; /* 根据需要设置卡片宽度 */
}
.login-code-img {
  width: 100%;
}
</style>
